package chapter25;

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class EchoClientToMultiThreadServer extends JFrame {
    // Text field for receiving radius

    private JTextField jtf = new JTextField();
    // Text area to display contents
    private JTextArea jta = new JTextArea();
    // IO streams
    private DataOutputStream toServer;
    private DataInputStream fromServer;

    public static void main(String[] args) {
        EchoClientToMultiThreadServer client = 
            new EchoClientToMultiThreadServer();
        
        while (true) {            
            client.autoReceive();
        }
    }

    public EchoClientToMultiThreadServer() {
        // Panel p to hold the label and text field
        JPanel p = new JPanel();
        p.setLayout(new BorderLayout());
        p.add(new JLabel("Enter text"), BorderLayout.WEST);
        p.add(jtf, BorderLayout.CENTER);
        jtf.setHorizontalAlignment(JTextField.RIGHT);

        setLayout(new BorderLayout());
        add(p, BorderLayout.NORTH);
        add(new JScrollPane(jta), BorderLayout.CENTER);

        jtf.addActionListener(new ButtonListener()); // Register listener

        setTitle("Echo Client");
        setSize(500, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true); // It is necessary to show the frame here!

        try {
            // Create a socket to connect to the server
//            Socket socket = new Socket("localhost", 8000);
            Socket socket = new Socket("10.100.2.24", 8000);
            // Socket socket = new Socket("130.254.204.36", 8000);
            // Socket socket = new Socket("drake.Armstrong.edu", 8000);

            // Create an input stream to receive data from the server
            fromServer = new DataInputStream(
                socket.getInputStream());

            // Create an output stream to send data to the server
            toServer =
                new DataOutputStream(socket.getOutputStream());
        }
        catch (IOException ex) {
            jta.append(ex.toString() + '\n');
        }
    }

    private void autoReceive() {
        try {
            // Get message from the server
            String message = fromServer.readUTF();

            // Display to the text area
            jta.append(message + "\n");
        }
        catch (IOException ex) {
            System.err.println(ex);
        }
    }

    private class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {

                // Get the text from the text field
                // and send it to the server
                toServer.writeUTF(jtf.getText());
                toServer.flush();
            }
            catch (IOException ex) {
                System.err.println(ex);
            }
        }
    }
}
